<template>
  <div class="common-container" style="min-height: calc(100vh - 60px)">
    <div class="common-content">
      <!-- 购物车头部 -->
      <div class="cart-header">
        <div class="header-item">
          <el-checkbox v-model="allChecked" @change="handleAllCheckedChange">全选</el-checkbox>
        </div>
        <div class="header-item header-item-product">商品信息</div>
        <div class="header-item">单价</div>
        <div class="header-item">数量</div>
        <div class="header-item">小计</div>
        <div class="header-item">操作</div>
      </div>

      <!-- 购物车商品列表 -->
      <div class="cart-list">
        <div v-for="item in cartItems" :key="item.id" class="cart-item">
          <div class="item-checkbox">
            <el-checkbox v-model="item.checked" @change="handleItemCheckedChange"></el-checkbox>
          </div>
          <div class="item-product" @click="goToDetail(item.productId)">
            <img :src="item.productImg" alt="商品图片" class="product-img">
            <div class="product-info">
              <div class="product-name">{{ item.productName }}</div>
              <div class="product-params" v-if="item.params">
                <span v-for="(value, key) in item.params" :key="key">{{ key }}: {{ value }}</span>
              </div>
            </div>
          </div>
          <div class="item-price">¥{{ item.price }}</div>
          <div class="item-quantity">
            <el-input-number v-model="item.quantity" :min="1" :max="item.stock"
              @change="handleQuantityChange(item.id, $event)" size="small"></el-input-number>
          </div>
          <div class="item-subtotal">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
          <div class="item-action">
            <el-button @click="handleRemove(item.id)" type="text" size="small" class="remove-btn">删除</el-button>
            <el-button @click="handleFavorite(item.id)" type="text" size="small" class="favorite-btn">收藏</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 空购物车状态 -->
    <div v-if="cartItems.length === 0 && !loading" class="empty-state">
      <el-empty description="购物车还是空的，快去逛逛吧～"></el-empty>
      <el-button type="primary" @click="goToGoodsList" style="margin-top: 20px">
        去购物
      </el-button>
    </div>

    <!-- 购物车底部结算 -->
    <div v-if="cartItems.length > 0" class="cart-footer">
      <div class="footer-left">
        <el-button @click="handleRemoveSelected" type="text" class="remove-selected-btn">
          删除选中
        </el-button>
      </div>
      <div class="footer-right">
        <div class="total-info">
          <span>已选 {{ selectedCount }} 件商品</span>
          <div class="total-price">
            合计：<span class="price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
        </div>
        <el-button @click="handleCheckout" type="primary" size="large" :disabled="!hasSelectedItems">
          结算
        </el-button>
      </div>
    </div>

    <!-- 加载中状态 -->
    <div v-loading="loading" class="loading-container" element-loading-text="加载中..."></div>
  </div>
</template>

<script>
export default {
  name: 'Cart',
  data() {
    return {
      cartItems: [],
      allChecked: false,
      loading: false,
      selectedCount: 0,
      totalPrice: 0
    };
  },
  computed: {
    hasSelectedItems() {
      return this.selectedCount > 0;
    }
  },
  created() {
    this.loadCartItems();
  },
  methods: {
    // 加载购物车商品
    loadCartItems() {
      this.loading = true;
      this.request.get('/cart').then(res => {
        this.loading = false;
        if (res.code === 200 && Array.isArray(res.data)) {
          // 对后端返回的数据进行映射和处理
          this.cartItems = res.data.map(item => ({
            id: item.id,
            productId: item.goodsId || item.productId,
            productName: item.goodsName || item.productName,
            productImg: item.img || item.imgUrl || item.productImg,
            price: item.price,
            quantity: item.num || item.quantity,
            stock: item.storage || item.stock || 999, // 使用storage字段获取库存信息，默认999
            checked: false,
            params: this.parseParams(item.specs || item.params)
          }));
          // 默认不选中任何商品
          this.updateSelectedState();
        } else {
          this.$message.error('获取购物车商品失败');
        }
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取购物车商品失败');
      });
    },

    // 解析商品参数
    parseParams(params) {
      if (!params) return null;
      try {
        if (typeof params === 'string') {
          return JSON.parse(params);
        } else if (typeof params === 'object') {
          return params;
        }
      } catch (e) {
        console.error('解析参数失败', e);
      }
      return null;
    },

    // 处理全选状态变化
    handleAllCheckedChange(value) {
      this.cartItems.forEach(item => {
        item.checked = value;
      });
      this.updateSelectedState();
    },

    // 处理单个商品选中状态变化
    handleItemCheckedChange() {
      this.updateSelectedState();
      // 检查是否所有商品都被选中
      this.allChecked = this.cartItems.length > 0 && this.cartItems.every(item => item.checked);
    },

    // 更新选中状态（数量和总价）
    updateSelectedState() {
      const selectedItems = this.cartItems.filter(item => item.checked);
      this.selectedCount = selectedItems.length;
      // 使用toFixed和parseFloat解决浮点数精度问题
      this.totalPrice = parseFloat(
        selectedItems.reduce((sum, item) => {
          const itemTotal = parseFloat((item.price * item.quantity).toFixed(2));
          return (parseFloat(sum.toFixed(2)) + itemTotal).toFixed(2);
        }, 0)
      );
    },

    // 处理数量变化
    handleQuantityChange(itemId, quantity) {
      const item = this.cartItems.find(i => i.id === itemId);

      // 立即更新合计金额
      this.updateSelectedState();

      // 强制重新渲染视图
      this.$forceUpdate();

      // 计算新的总价
      const newTotal = item.price * quantity;

      // 更新到后端
      this.request.post('/cart', {
        id: itemId,
        num: quantity,
        price: item.price,
        total: newTotal
      }).then(res => {
        if (res.code === 200) {
          // 更新成功，不需要额外操作，因为已经在前端更新了
          console.log('购物车数量更新成功');
        } else {
          // 更新失败，回滚数量并显示错误
          this.$message.error(res.msg || '更新数量失败');
        }
      }).catch(error => {
        // 网络错误，回滚数量并显示错误
        this.$message.error('网络错误，更新数量失败');
      });
  },

  // 删除商品
  handleRemove(itemId) {
    this.$confirm('确定要从购物车中删除该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.request.delete(`/cart/${itemId}`).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.loadCartItems();
        } else {
          this.$message.error(res.msg || '删除失败');
        }
      }).catch(() => {
        this.$message.error('删除失败');
      });
    }).catch(() => {
      // 用户取消操作
    });
  },

  // 删除选中商品
  handleRemoveSelected() {
    const selectedIds = this.cartItems
      .filter(item => item.checked)
      .map(item => item.id);

    if (selectedIds.length === 0) {
      this.$message.warning('请选择要删除的商品');
      return;
    }

    this.$confirm(`确定要删除选中的 ${selectedIds.length} 件商品吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 批量删除
      this.request.delete('/cart/batch', {
        data: selectedIds
      }).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.loadCartItems();
        } else {
          this.$message.error(res.msg || '删除失败');
        }
      }).catch(() => {
        this.$message.error('删除失败');
      });
    }).catch(() => {
      // 用户取消操作
    });
  },

  // 添加到收藏
  handleFavorite(itemId) {
    const item = this.cartItems.find(i => i.id === itemId);
    if (!item) return;

    this.request.post('/collect', {
      goodsId: item.productId
    }).then(res => {
      if (res.code === 200) {
        this.$message.success('收藏成功');
      } else {
        this.$message.error(res.msg || '收藏失败');
      }
    }).catch(() => {
      this.$message.error('收藏失败');
    });
  },

  // 前往商品详情
  goToDetail(productId) {
    this.$router.push(`/front/goodsDetail/${productId}`);
  },

  // 前往商品列表
  goToGoodsList() {
    this.$router.push('/front/goodsList');
  },

  // 结算
  handleCheckout() {
    const selectedItems = this.cartItems.filter(item => item.checked);
    if (selectedItems.length === 0) {
      this.$message.warning('请选择要结算的商品');
      return;
    }

    // 构建订单参数
    const orderParams = {
      goods: selectedItems.map(item => ({
        goodsId: item.productId,
        num: item.quantity
      })),
      totalAmount: this.totalPrice
    };

    // 保存订单参数到路由状态中，然后跳转到确认订单页面
    this.$router.push({
      path: '/front/checkout',
      query: {
        orderParams: JSON.stringify(orderParams)
      }
    });
  }
}
};
</script>

<style scoped>
.common-container {
  padding: 0;
}

.common-content {
  margin-bottom: 20px;
}

.cart-header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background-color: #f5f5f5;
  border-radius: 4px 4px 0 0;
  font-weight: bold;
  color: #606266;
}

.header-item {
  flex: 1;
  text-align: center;
}

.header-item-product {
  flex: 3;
  text-align: left;
}

.cart-list {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-top: none;
  border-radius: 0 0 4px 4px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-checkbox {
  flex: 1;
  display: flex;
  justify-content: center;
}

.item-product {
  flex: 3;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.product-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
  border: 1px solid #ebeef5;
}

.product-info {
  flex: 1;
}

.product-name {
  color: #303133;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-params {
  color: #909399;
  font-size: 12px;
}

.product-params span {
  margin-right: 10px;
}

.item-price,
.item-quantity,
.item-subtotal,
.item-action {
  flex: 1;
  text-align: center;
}

.item-price,
.item-subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.remove-btn {
  color: #909399;
  margin-right: 10px;
}

.remove-btn:hover {
  color: #f56c6c;
}

.favorite-btn {
  color: #909399;
}

.favorite-btn:hover {
  color: #e6a23c;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  background-color: #fff;
  border-radius: 4px;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.footer-left {
  flex: 1;
}

.remove-selected-btn {
  color: #909399;
}

.remove-selected-btn:hover {
  color: #f56c6c;
}

.footer-right {
  display: flex;
  align-items: center;
}

.total-info {
  margin-right: 30px;
  text-align: right;
}

.total-info span {
  color: #606266;
  margin-right: 20px;
}

.total-price {
  margin-top: 10px;
}

.price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}

.loading-container {
  background-color: #fff;
  padding: 40px;
  text-align: center;
}
</style>